package com.thinkgem.jeesite.kpoint.core.mybatisplus;

import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import com.baomidou.mybatisplus.extension.injector.AbstractLogicMethod;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

/**
 * @Author:Kongxiangsheng
 * @DesCription:
 * @Date:Created in 3:34 2018/12/16
 * @Modified By:
 */
public class LogicSelectByEntity extends AbstractLogicMethod {
    private static String WRAPPER_NULL = "";

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        // 主要是用这个sqlMethod的sql语句，名称是自定义的
        SqlMethod sqlMethod = SqlMethod.SELECT_LIST;
        String method = "selectByEntity";

        String selectColumns = this.sqlSelectColumns(tableInfo, false);

        String sql = String.format(sqlMethod.getSql(), selectColumns, tableInfo.getTableName(), sqlWhereByEntity(true, tableInfo));
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);

        return addSelectMappedStatement(mapperClass, method, sqlSource, modelClass, tableInfo);
    }

    private String sqlWhereByEntity(boolean newLine, TableInfo table) {
        boolean isLogicDelete = table.isLogicDelete();

        String sqlScript = table.getAllSqlWhere(isLogicDelete, true, WRAPPER_NULL);
        if (isLogicDelete) {
            sqlScript += (NEWLINE + table.getLogicDeleteSql(true, false));
        }
        sqlScript += NEWLINE;
        sqlScript = SqlScriptUtils.convertWhere(sqlScript) + NEWLINE;


        return newLine ? NEWLINE + sqlScript : sqlScript;
    }
}
